package com.atguigu.util;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import io.minio.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;


public class MinioUploadUtil {
   public static String upload(MultipartFile file,String endpointUrl,String user,String password,String bucketName) throws Exception{
           MinioClient minioClient =
                   MinioClient.builder()
                           .endpoint(endpointUrl)
                           .credentials(user, password)
                           .build();
           boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
           if (!found) {
               minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
           }
           String name = file.getOriginalFilename();
       if(name==null){
           throw new Exception();
       }
           String suffix = name.substring(name.lastIndexOf("."));
           String newName=DateUtil.format(new Date(),"yyyyMMdd")+UUID.randomUUID().toString().replace("-","")+suffix;
       minioClient.putObject(
               PutObjectArgs.builder()
                       .bucket(bucketName)
                       .stream(file.getInputStream(),file.getSize(),-1)
                       .object(newName)
                       .build());
       String urlPrefix=endpointUrl+"/"+bucketName+"/";
       return urlPrefix+newName;
   }
}
